package cn.wolfcode.shop.web.frontend;

import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.domain.SeckillGood;
import cn.wolfcode.shop.redis.RedisTemplate;
import cn.wolfcode.shop.redis.SeckillServerKeyPrefix;
import cn.wolfcode.shop.service.ISeckillGoodService;
import cn.wolfcode.shop.vo.SeckillGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("seckillGood")
public class SeckillGoodController {

    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private RedisTemplate redisTemplate;

    // QPS: 每秒钟能处理的请求数
    // 优化前 QPS: 500 * 10的情况下  qps=140
    // 优化后 QPS: 500 * 10的情况下  qps=212
    // 优化后 QPS: 300 * 10的情况下  qps=260
    @RequestMapping("query")
    public Result<List<SeckillGoodVo>> query(){
        return Result.success(seckillGoodService.queryByCache());
    }

    @RequestMapping("find")
    public Result<SeckillGood> find(Long seckillGoodId){
        SeckillGoodVo seckillGoodVo = seckillGoodService.find(seckillGoodId);
        Integer stock = redisTemplate.get(SeckillServerKeyPrefix.SECKILL_GOOD_STOCK, seckillGoodId + "", Integer.class);
        seckillGoodVo.setStockCount(stock>0?stock:0);
        return Result.success(seckillGoodVo);
    }

    @RequestMapping("initData")
    public Result<String> initData(){
        List<SeckillGoodVo> list = seckillGoodService.query();
        for(SeckillGoodVo vo : list){
            redisTemplate.hset(SeckillServerKeyPrefix.SECKILL_GOODS_HASH,"",vo.getId()+"",vo);
            redisTemplate.set(SeckillServerKeyPrefix.SECKILL_GOOD_STOCK,vo.getId()+"",vo.getStockCount());
        }
        return Result.success("");
    }
}
